//
//  WmcFeedbackFooterView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/1.
//

import UIKit

class WmcFeedbackFooterView: WmcBaseView {
    // Internal

    var submitClosure: (() -> Void)?

    lazy var submitBtn: UIButton = {
        let btn = UIButton.Wmc_themeColorBtn(color: .wmc_mainTheme, title: "提交")
        return btn
    }()

    lazy var scanLabel: UILabel = {
        let label = UILabel.YP.Create(text: "扫码添加客服微信",
                                      font: 16.yp.uiFont(weight: .medium),
                                      color: UIColor.wmc_grayH8_8A8A99,
                                      alignment: .center)
        label.isHidden = true
        return label
    }()

    lazy var qrCodeImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.isHidden = true
        imageView.image = "image_placeholder".wmc_image
        return imageView
    }()

    lazy var saveQrCodeBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "保存二维码", image: "feedback_qr_icon".wmc_image)
        btn.backgroundColor = .wmc_mainTheme
        btn.font = 14.wmc_font
        btn.contentEdge = .YP.Create(horizontal: 20, vertical: 6)
        btn.imgSize = 25
        btn.layer.cornerRadius = 35.0 / 2.0
        btn.layer.masksToBounds = true
        btn.isHidden = true
        return btn
    }()

    /// 复制微信号
    lazy var wechatLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14)
        return label
    }()

    override func makeUI() {
        backgroundColor = .wmc_grayH19_F5F5F5

        addSubview(submitBtn)
        submitBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(32)
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.height.equalTo(44)
        }

        addSubview(scanLabel)
        scanLabel.snp.makeConstraints { make in
            make.top.equalTo(submitBtn.snp.bottom).offset(40)
            make.left.right.equalToSuperview()
            make.height.equalTo(22)
        }

        qrCodeImageView.backgroundColor = .wmc_grayH14_CCCCCC
        addSubview(qrCodeImageView)
        qrCodeImageView.snp.makeConstraints { make in
            make.top.equalTo(scanLabel.snp.bottom).offset(15)
            make.centerX.equalToSuperview()
            make.size.equalTo(140.wmc_autoHor)
        }

        addSubview(saveQrCodeBtn)
        saveQrCodeBtn.snp.makeConstraints { make in
            make.top.equalTo(qrCodeImageView.snp.bottom).offset(7)
            make.centerX.equalToSuperview()
            make.width.equalTo(qrCodeImageView)
            make.height.equalTo(35)
        }

        addSubview(wechatView)
        wechatView.snp.makeConstraints { make in
            make.top.equalTo(saveQrCodeBtn.snp.bottom).offset(12)
            make.centerX.equalToSuperview()
            make.height.equalTo(35)
//            make.width.equalTo(200)
        }

        wechatView.addSubview(wechatLabel)
        wechatLabel.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.right.equalTo(-45)
            make.width.greaterThanOrEqualTo(100)
        }

        wechatView.addSubview(copyBtn)
        copyBtn.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.width.equalTo(40)
        }
    }

    func bindModel(_ model: WmcWechatModel?) {
        guard let model = model else {
            return
        }

        self.model = model

        if !model.imgUrl.isEmpty {
            qrCodeImageView.kf.setImage(with: URL(string: model.imgUrl), placeholder: "feedback_qr_icon".wmc_image)
            scanLabel.isHidden = false
            qrCodeImageView.isHidden = false
            saveQrCodeBtn.isHidden = false
        }

        if !model.wechatId.isEmpty {
            wechatLabel.text = "微信号：\(model.wechatId)"
            wechatView.isHidden = false

            if model.imgUrl.isEmpty {
                wechatView.snp.remakeConstraints { make in
                    make.top.equalTo(submitBtn.snp.bottom).offset(40)
                    make.centerX.equalToSuperview()
                    make.height.equalTo(35)
                }
            }
        }
    }

    override func bindViewAction() {
        submitBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self else {
                return
            }
            weakSelf.submitClosure?()
        }.disposed(by: rx.disposeBag)

        saveQrCodeBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self, let image = weakSelf.qrCodeImageView.image else { return }
            weakSelf.saveImageToPhotoLibrary(image: image)
        }.disposed(by: rx.disposeBag)

        copyBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self, let wechatId = weakSelf.model?.wechatId, !wechatId.isEmpty else { return }
            UIPasteboard.general.string = wechatId
            WmcHudManager.toast("复制成功")
        }.disposed(by: rx.disposeBag)
    }

    // Private

    private lazy var wechatView: UIView = {
        let view = UIView()
        view.isHidden = true
        return view
    }()

    private lazy var copyBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("复制", for: .normal)
        btn.setTitleColor(UIColor.wmc_mainTheme, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14)
        return btn
    }()

    private var model: WmcWechatModel?

    private func saveImageToPhotoLibrary(image: UIImage) {
        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable {
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(_:didFinishSaving:contextInfo:)), nil)
        } else {
            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
        }
    }

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("保存成功")
        }
    }
}
